package com.zimu.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zimu.api.mapper.UserInterfaceInfoMapper;
import com.zimu.common.model.dto.userinterfaceinfo.UserInterfaceInfoUpdateRequest;
import com.zimu.common.model.entity.UserInterfaceInfo;
import com.zimu.common.service.CommonUserInterfaceInfoService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
@DubboService
public class CommonUserInterfaceInfoImpl implements CommonUserInterfaceInfoService {
    @Resource
    UserInterfaceInfoMapper userInterfaceInfoMapper;
    @Override
    @Transactional
    public boolean addInvokeNum(UserInterfaceInfoUpdateRequest updateRequest) {
        QueryWrapper<UserInterfaceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",updateRequest.getUserId())
                .eq("interfaceInfoId",updateRequest.getInterfaceInfoId());
        UserInterfaceInfo userInterfaceInfo = userInterfaceInfoMapper.selectOne(queryWrapper);
        //首次调用该接口，送他五次,
        if (userInterfaceInfo == null){
            userInterfaceInfo = new UserInterfaceInfo();
            userInterfaceInfo.setInterfaceInfoId(updateRequest.getInterfaceInfoId());
            userInterfaceInfo.setUserId(updateRequest.getUserId());
            //扣除调用的一次
            userInterfaceInfo.setTotalNum(1);
            userInterfaceInfo.setLeftNum(4);
            userInterfaceInfoMapper.insert(userInterfaceInfo);
            return true;
        }else {
            //无可调用次数
            if (userInterfaceInfo.getLeftNum() == 0 )
                return false;
            UserInterfaceInfo updateInterfaceInfo = new UserInterfaceInfo();
            updateInterfaceInfo.setId(userInterfaceInfo.getId());
            updateInterfaceInfo.setTotalNum(userInterfaceInfo.getTotalNum() + 1 );
            updateInterfaceInfo.setLeftNum(userInterfaceInfo.getLeftNum() - 1 );
            userInterfaceInfoMapper.updateById(updateInterfaceInfo);
        }
        return true;
    }
}
